
#include "StdAfx.h"
#include "CmdLine.h"
#include <stdarg.h>

#include "Work.h"

CmdLine::CmdLine( char* title, WorkListener* worker ){	
	worker_ = worker;

	print( " " );

	if( title )
		print( title );
	else
		print( "welcome..." );

	prompt_ = "> ";
	print_prompt();
}

CmdLine::~CmdLine(){
}

void CmdLine::wait_cmd(){
	char ch = 0;

	while( 1 ){
		ch = getchar();
		buf_ += ch;

		if( ch == 10 ){
			buf_ += '\0';
			
			if( worker_ )
				worker_->workPerformed( 0, buf_.toCharacters() );
			else
				return;

			buf_.clear();
		}
	}
}

void CmdLine::make_prompt(){
	prompt_ += "test_terminal";
	prompt_ += "@";
	prompt_ += "name";
	prompt_ += "> ";
}

void CmdLine::print_to_prompt( char* msg ){	
	print( "%s%s", msg, "\r\n" );
	print_prompt();
}

void CmdLine::print_prompt(){	
	BlanketLock lock( &lock_ );
	
	printf( "%s ", prompt_.toCharacters() );
}

void CmdLine::print( char* pFmt, ...  ){
	BlanketLock lock( &lock_ );

	if(! pFmt )
		return;

	va_list	vaList;
	va_start( vaList, pFmt );

	char buffer[ DEF_BYTE_PER_HIGHER ];
	memset( buffer, 0, DEF_BYTE_PER_HIGHER );
	buffer[ 0 ] = ' ';

#ifdef WIN32
	_vsntprintf( &(buffer[ 1 ] ), DEF_BYTE_PER_HIGHER, (const char *)pFmt, vaList );
#else
	vsnprintf( &(buffer[ 1 ] ), DEF_BYTE_PER_HIGHER, (const char *)pFmt, vaList );
#endif

	printf( buffer );

	va_end( vaList );	
}

void CmdLine::print_error( char* pFmt, ... ){
	BlanketLock lock( &lock_ );

	if(! pFmt )
		return;

	va_list	vaList;
	va_start( vaList, pFmt );

	char buffer[ DEF_BYTE_PER_HIGHER ];
	memset( buffer, 0, DEF_BYTE_PER_HIGHER );

	strncpy( buffer, "  error : ", strlen("  error : ") );

#ifdef WIN32
	_vsntprintf( &(buffer[ strlen( buffer ) ]), DEF_BYTE_PER_HIGHER, (const char *)pFmt, vaList );
#else
	vsnprintf( &(buffer[ strlen( buffer ) ]), DEF_BYTE_PER_HIGHER, (const char *)pFmt, vaList );
#endif

	strcat( buffer, "\r\n" );

	printf( buffer );

	va_end( vaList );

	printf( "%s ", prompt_.toCharacters() );
}
